package hashTable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class N350_IntersectionOfTwoArraysII {
    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1);
        }

        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> list = new ArrayList<>();
        for (int key : nums1) {
            Integer value = map.getOrDefault(key, 0);
            map.put(key, value + 1);
        }

        for (int num : nums2) {
            if (map.getOrDefault(num, 0) > 0) {
                list.add(num);
                map.put(num, map.get(num) - 1);
            }
        }

        int index = 0;
        int[] arr = new int[list.size()];
        for (Integer i : list) {
            arr[index++] = i;
        }
        return arr;
    }

    public static void main(String[] args) {
        N350_IntersectionOfTwoArraysII solution = new N350_IntersectionOfTwoArraysII();
        int[] num1 = {4, 9, 5}, num2 = {9, 4, 9, 8, 4};
        int[] nums = solution.intersect(num1, num2);
        for (int num : nums) {
            System.out.print(num + " ");
        }
    }
}
